package com.ygxsk.carhome.ui.care;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CardAuditStatus;
import com.ygxsk.carhome.event.EventCardMain;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.CardMainBottomAdapter;
import com.ygxsk.carhome.ui.zxing.MyBGAQRCodeActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-25  12:03
 * @Description:卡券发放的主要列表,2023年10月7日11:34:21 以前是仅仅只有优惠券的列表，后边又新增了 优惠大礼包的需求；
 *
 */
public class CardMainActivity extends ErrorActivity implements ErrorParentExtraSingle {

    //添加布局的刷新一个能力
    @BindView(R.id.refreshlayoutincardsend)
    SmartRefreshLayout refreshLayoutInCardSend;

//    private PopupWindow mPopupWindow;
//    private AnimUtil animUtil;

    //底部的列表布局
    @BindView(R.id.recyclerviewincardmainbottom)
    RecyclerView recyclerViewInCardMainBottom;

    //该页面的优惠券发放的历史记录
    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<>();

    //添加
    private CardMainBottomAdapter cardMainBottomAdapter;
    /**
     * 最后一条上传的id的信息内容
     */
    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    //选择的这个客户的id ,用在发送 优惠券上；
    private String customerId_upLoad;

    private CustomAttachPopupBg customAttachPopupBg;


    //跳转到历史记录页面
    private void method_go_history(boolean extra_ischecked_more_items_flag, String couponPackId_upLoad) {

        Bundle extra_bundle = new Bundle();
        //携带是从哪个页面过去的？
        //携带标志 是从 客户关怀过去的
        extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);

        //是否是批量审核跳转携带值内容
        extra_bundle.putBoolean(ExtraKey.EXTRA_ISCHECKED_MORE_ITEMS_FLAG, extra_ischecked_more_items_flag);

        //携带优惠券本身属于哪一个优惠券大礼包下的 优惠券大礼包id: EXTRA_COUPONPACKID_UPLOAD
        extra_bundle.putString(ExtraKey.EXTRA_COUPONPACKID_UPLOAD, couponPackId_upLoad);

        ActivityUtils.startActivity(extra_bundle, CardSumHistoryActivity.class);

    }

//    @OnClick({R.id.constraintlayoutheadersmartgo})
//    public void ClickInCardMain(View view) {
//
//        KeyboardUtils.hideSoftInput(CardMainActivity.this);
//
//        switch (view.getId()) {
//
//            case R.id.constraintlayoutheadersmartgo: {//跳转历史记录，不是批量审核筛选标志
//
//                //2024-1-2 不是批量审核，那么传递0，过去之后再以零做判断
//                method_go_history(false, ConstantSign.NUMBER_ZERO);
//
//                break;
//            }
//
//            default:
//                break;
//        }
//
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

//        if (mDataResources_couponCustomer == null) {
//            mDataResources_couponCustomer = new ArrayList<>();
//        }
//
//        if (mDataResources_greatPackageCustomer == null) {
//            mDataResources_greatPackageCustomer = new ArrayList<>();
//        }
//
//        if (mDataResources_customerPerson_outSide == null) {
//            mDataResources_customerPerson_outSide = new ArrayList<>();
//        }

        processExtraData();

        initloading();

        initViews();

        //这里有页面刷新，或者编辑完毕，通知页面刷新的逻辑；
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        gainDatas();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_card_main;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.customer_carecustom));

        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //右侧暂时没有文字
        toolbarHelper.setLayoutRight(false, 0, "", null);

        //2024-1-10 14:00:58新增的特殊图片
        toolbarHelper.setImageViewRight(true, R.drawable.icon_rigad, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                new XPopup.Builder(mActivityInstance)
//                        .hasShadowBg(false)
//                        .isTouchThrough(true)
//                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
////                        .atView(toolbarHelper.getImageViewRight())
////                        .atView(toolbarHelper.getToolbar().findViewById(R.id.imageviewinphone))
//                        .atView(imageViewRight)
//                        .isCenterHorizontal(true)
//                        .hasShadowBg(false) // 去掉半透明背景
//                        .asCustom(new RightBubbleAttachPopup(mActivityInstance))
//                        .show();

//                showPop();
//                toggleBright();

                customAttachPopupBg = (CustomAttachPopupBg) new XPopup.Builder(mActivityInstance)
                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                        .isCoverSoftInput(false)//
                        .atView(v)
                        .hasShadowBg(true)//是否展示背景
                        .asCustom(new CustomAttachPopupBg(mActivityInstance, mActivityInstance, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                                    requestCodeQRCodePermissions();
                                } else {
                                    requestCodePermissionsXXPermissions();
                                }

                            }
                        }))
                        .show();

            }
        });

        //右侧是【编辑】
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_cardverifi_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//                //携带是 客户关怀 过去的 到卡券核销列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//                ActivityUtils.startActivity(extra_bundle, CardDistHistoryActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //---------------------------------------------------------------------------------------------
        //默认是遮盖的，因为要到搜索客户之后立即调用这个客户的信息
        //fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

        //布局的适配器填充，下拉刷新等等；
        recyclerViewInCardMainBottom.setLayoutManager(new MyLinearLayoutManager(this));
        cardMainBottomAdapter = new CardMainBottomAdapter(flag_jumpfrom_where, R.layout.smartgolistadapter, mDataResources);
        recyclerViewInCardMainBottom.setAdapter(cardMainBottomAdapter);
        cardMainBottomAdapter.notifyDataSetChanged();

        //这里添加一个header展示发放记录的；
        //smartGoItemAdapter.removeAllHeaderView();
        //smartGoItemAdapter.addHeaderView(getHeaderView(recyclerViewInSmartGo));

        cardMainBottomAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //仅仅复制手机号码
                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                switch (view.getId()) {

                    case R.id.imagerightinfoclick: {//查看优惠券的发送原因

                        if (couponCustomerVo != null) {

//                            String couponName = couponCustomerVo.getCouponName();
//                            String explain = couponCustomerVo.getExplain();
                            CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());

                        }

                        break;
                    }

                    case R.id.textviewcarsendreason: {//查看原因的文字

                        if (couponCustomerVo != null) {

//                            String explain = couponCustomerVo.getExplain();
//                            String couponName = couponCustomerVo.getCouponName();
                            CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());
                        }


                        break;

                    }

                    case R.id.textvieweditviewphonecarsmart: {

                        if (couponCustomerVo != null) {

                            clickButton_toCallPhone(CardMainActivity.this, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());

                            //同时复制
//                    if (!TextUtils.isEmpty(couponCustomerVo.getPhone())) {
//                        CommUtils.methodCopyClip(couponCustomerVo.getPhone(),true);
//                    }else{
//                        ToastUtils.showShort(R.string.hasfailgetphonenumber);
//                    }

                        }

                        break;
                    }

                    case R.id.roundtextViewDoVerifyMoreItems: {//【批量审核】按钮

                        //历史记录页面，做批量审核。
                        method_go_history(true, String.valueOf(couponCustomerVo.getCouponPackId()));

                        break;
                    }

                    case R.id.roundtextViewDoVerifyOne: {//审核按钮

                        if (couponCustomerVo != null) {

                            CommUtils.checkDialog(mAlertView);
                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                    StringUtils.getString(R.string.submit_consign_verify_message_sure),//提示内容 确定审核通过
                                    StringUtils.getString(R.string.clearcachecancel), //取消
                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                                @Override
                                public void onItemClick(Object o, int position) {

                                    if (position != AlertView.CANCELPOSITION) {

                                        //"couponCustomerId": 62986, //发放的优惠券记录主键Id
                                        //"couponId": 1, //优惠券主键Id
                                        //"auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
                                        method_gainVerifySubmitInfo_upLoad(couponCustomerVo.getCouponCustomerId(), couponCustomerVo.getCouponId(), couponCustomerVo.getAuditStatus());

                                    }

                                }
                            });

                            mAlertView.setCancelable(true);
                            mAlertView.show();

                        }

                        break;
                    }

                    default:
                        break;
                }

            }
        });


        if (refreshLayoutInCardSend != null) {

            refreshLayoutInCardSend.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            getServerDatasCardHistory();

                            refreshLayout.finishLoadMore();

                        }
                    });

                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            gainDatas();

                            refreshLayout.finishRefresh();

                        }
                    });

                }
            });
        }

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        //这个接口内就是刷新全部内容
        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardMainBottomAdapter != null) {
            cardMainBottomAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            //同时间获取卡券类型的列表
//            getServerDatasCouponType(null);

            //这个次要，如果没有直接不展示也可以，但是卡券类型必须先获取为了提交数据；
            getServerDatasCardHistory();

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
            // : 2023-08-14 15:22 添加页面遮盖，使用adapter自有的方式来填充
            setEnableLoadmore(refreshLayoutInCardSend, false);

        }

    }


    //获取的优惠券的历史：历史记录--这个员工发放过的 优惠券 有张三-李四-王五的；
    private void getServerDatasCardHistory() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEFORMEMBER_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageForMember_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponListPageForMember(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        // : 2023-08-15 14:32 这里还有更好的处理办法，使用BRAV自己的遮盖

//                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardMainBottom);
//                        }

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            setEnableLoadmore(refreshLayoutInCardSend, false);

                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        if (refreshLayoutInCardSend.getState() == RefreshState.Refreshing) {

                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "目前正处于 下拉刷新状态，所以展示  加载更多");

                            method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                        }

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInCardSend, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //有加载更多 不需要这样
//                        if (mDataResources != null && !mDataResources.isEmpty()) {
//                            mDataResources.clear();
//                        }

                        if (couponCustomerVoOutSide != null) {

                            ArrayList<CouponCustomerVo> couponCustomerVos = couponCustomerVoOutSide.getDataList();

                            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(couponCustomerVos);
                                }
                            }

                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardMainBottom);
                            setEnableLoadmore(refreshLayoutInCardSend, false);
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

                        }

                        if (cardMainBottomAdapter != null) {
                            cardMainBottomAdapter.notifyDataSetChanged();
                        }

                        pagination_upLoad = couponCustomerVoOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInCardSend, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInCardSend, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    //优惠券的发放历史的审核状态；
    private void method_gainVerifySubmitInfo_upLoad(Integer _couponCustomerId, String _couponId, Integer _auditStatus) {

//        {
//                "couponCustomerId": 62986, //发放的优惠券记录主键Id
//                "couponId": 1, //优惠券主键Id
//                "auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
//        }

//        CardAuditStatus {
//            //审核状态 0：待审核 1：审核通过 2：审核不通过
//                    STATUS_NOT_VERIFY("0", "待审核"),
//                    STATUS_HAS_VERIFY("1", "审核通过"),
//                    STATUS_CANNOT_VERIFY("2", "审核不通过");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.couponCustomerId, _couponCustomerId);//
        map.put(Parameterkey.couponId, _couponId);
        map.put(Parameterkey.auditStatus, CardAuditStatus.STATUS_HAS_VERIFY.getIndex());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEAUDITSTATUS_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateAuditStatus_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateAuditStatus(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        methodSubmitSuccess(CardMainActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                //通知主页列表刷新
                                pagination_upLoad = Parameterkey.pageNum_default_first;

                                if (mDataResources != null && !mDataResources.isEmpty()) {
                                    mDataResources.clear();
                                }

                                if (cardMainBottomAdapter != null) {
                                    cardMainBottomAdapter.notifyDataSetChanged();
                                }

                                getServerDatasCardHistory();

                            }
                        });

//                        methodSubmitSuccess(ConsignMainActivity.this, new DoSomeThingListener() {
//                            @Override
//                            public void doSomeThing() {
//                                //应该是仅仅刷新列表即可
//                            }
//                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCardMain(EventCardMain eventCardMain) {

        if (eventCardMain != null) {

            if (eventCardMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "收到刷新主页列表的消息--EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST");

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardMainBottomAdapter != null) {
                    cardMainBottomAdapter.notifyDataSetChanged();
                }

                getServerDatasCardHistory();

            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardMainBottomAdapter != null) {
            cardMainBottomAdapter.notifyDataSetChanged();
            cardMainBottomAdapter = null;
        }

//        if (basePopupViewCardTypeOrgreatPackage != null) {
//            basePopupViewCardTypeOrgreatPackage.onDestroy();
//            basePopupViewCardTypeOrgreatPackage = null;
//        }
//
//        if (basePopupView_customerPerson != null) {
//            basePopupView_customerPerson.onDestroy();
//            basePopupView_customerPerson = null;
//        }

        if (customAttachPopupBg != null) {

            if (customAttachPopupBg.isShow()) {
                customAttachPopupBg.onDismiss();
            }

            customAttachPopupBg.onDestroy();
            customAttachPopupBg = null;
        }

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {

        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }

    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

        }

    }

//    private void showPop() {
//
//        // 设置布局文件
//        mPopupWindow.setContentView(LayoutInflater.from(this).inflate(R.layout.right_bubble_attach_popup, null));
//        // 为了避免部分机型不显示，我们需要重新设置一下宽高
//        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
//        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        // 设置pop透明效果
////        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
////        mPopupWindow.setBackgroundDrawable(new ColorDrawable(R.color.white));
//        mPopupWindow.setBackgroundDrawable(new ColorDrawable(getColor(R.color.white)));
//        // 设置pop出入动画
//        mPopupWindow.setAnimationStyle(R.style.pop_add);
//        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
//        mPopupWindow.setFocusable(true);
//        // 设置pop可点击，为false点击事件无效，默认为true
//        mPopupWindow.setTouchable(true);
//        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
//        mPopupWindow.setOutsideTouchable(true);
//        // 相对于 + 号正下面，同时可以设置偏移量
//        mPopupWindow.showAsDropDown(imageViewRight, -100, 50);
//        // 设置pop关闭监听，用于改变背景透明度
//        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
////                toggleBright();
//            }
//        });
//
//        //点击事件内容：
//        LinearLayout linearlayout_push = (LinearLayout) mPopupWindow.getContentView().findViewById(R.id.linearlayout_push);
//        LinearLayout linearlayout_dist = (LinearLayout) mPopupWindow.getContentView().findViewById(R.id.linearlayout_dist);
//
//        linearlayout_push.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //
//
//                //                携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//                //携带是 客户关怀 过去的 到卡券核销列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//                ActivityUtils.startActivity(extra_bundle, CardMainPushActivity.class);
//
//            }
//        });
//
//        linearlayout_dist.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
////                携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//                //携带是 客户关怀 过去的 到卡券核销列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//                ActivityUtils.startActivity(extra_bundle, CardDistHistoryActivity.class);
//
//            }
//        });
//
//    }

//    private static final long DURATION = 500;
//    private static final float START_ALPHA = 0.7f;
//    private static final float END_ALPHA = 1f;
//
//    private float bgAlpha = 1f;
//    private boolean bright = false;

//    private void toggleBright() {
//
//        // 三个参数分别为：起始值 结束值 时长，那么整个动画回调过来的值就是从0.5f--1f的
//        animUtil.setValueAnimator(START_ALPHA, END_ALPHA, DURATION);
//        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
//            @Override
//            public void progress(float progress) {
//                // 此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
//                bgAlpha = bright ? progress : (START_ALPHA + END_ALPHA - progress);
//                backgroundAlpha(bgAlpha);
//            }
//        });
//        animUtil.addEndListner(new AnimUtil.EndListener() {
//            @Override
//            public void endUpdate(Animator animator) {
//                // 在一次动画结束的时候，翻转状态
//                bright = !bright;
//            }
//        });
//        animUtil.startAnimator();
//    }

    /**
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
//    private void backgroundAlpha(float bgAlpha) {
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        // 0.0-1.0
//        lp.alpha = bgAlpha;
//        getWindow().setAttributes(lp);
//        // everything behind this window will be dimmed.
//        // 此方法用来设置浮动层，防止部分手机变暗无效
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//    }


    //android13的权限判断内容
    private void requestCodePermissionsXXPermissions() {

        try {

            //do

            if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.CAMERA)//
                    || !XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        XXPermissions.with(mActivityInstance)
                                // 适配分区存储应该这样写
                                //.permission(Permission.Group.STORAGE)
                                // 不适配分区存储应该这样写
                                .permission(com.hjq.permissions.Permission.CAMERA)//
                                .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                                //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                                .request(new OnPermissionCallback() {

                                    @Override
                                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                        if (!allGranted) {
                                            // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过
                                            return;
                                        }

                                        Toaster.show(String.format(mActivityInstance.getResources().getString(R.string.demo_obtain_permission_success_hint), PermissionNameConvert.getPermissionString(mActivityInstance, permissions)));

                                        openMain();

                                    }
                                });
                    }
                });

            } else {

                openMain();

            }


        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }


    }

    private void requestCodeQRCodePermissions() {

        if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    //2018年06月05日发现这里添加SD卡的存储权限内容
                    AndPermission.with(mActivityInstance)//
                            .runtime()//
                            .permission(
                                    Permission.CAMERA,//
                                    Permission.READ_EXTERNAL_STORAGE,//
                                    Permission.WRITE_EXTERNAL_STORAGE)//
                            .rationale(new RuntimeRationale())//
                            .onGranted(new Action<List<String>>() {//
                                @Override
                                public void onAction(List<String> permissions) {

                                    openMain();

                                }
                            }).onDenied(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> permissions) {
                                    //弹出失败弹窗
                                    if (AndPermission.hasAlwaysDeniedPermission(mActivityInstance, permissions)) {//
                                        (new PermissionSetting(mActivityInstance)).showSetting(ConstantApi.PERMISSION_NORMAL, mActivityInstance, permissions);//
                                    }
                                }
                            }).start();

                }
            });

        } else {

            openMain();

        }

    }

    //打开扫描二维码的能力
    private void openMain() {

        Bundle bundle = new Bundle();
        bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
        bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY);
        ActivityUtils.startActivity(bundle, MyBGAQRCodeActivity.class);

//        dismiss();

    }


}